#include "SpriteScript.h"
#include "clazz.h"
#include "T_Text.h"
#include "T_Sprite.h"
#include "CodingConvert.h"

static int text_setText(lua_State *L){
	T_Text *txt = (T_Text *)ModuleCheck(L,1,"Text");
	wchar_t *str = CharToWchar(luaL_checkstring(L,2));
	txt->setText(str);
	delete[] str;
	return 0;
}

static int text_setFontSize(lua_State *L){
	T_Text *txt = (T_Text *)ModuleCheck(L,1,"Text");
	txt->setFontSize((REAL)luaL_checknumber(L,2));
	return 0;
}

static int text_setColor(lua_State *L){
	T_Text *txt = (T_Text *)ModuleCheck(L,1,"Text");
	Gdiplus::Color *color = (Gdiplus::Color *)ModuleCheck(L,2,"Color");
	txt->setColor(*color);
	return 0;
}

static int text_setFont(lua_State *L){
	T_Text *txt = (T_Text *)ModuleCheck(L,1,"Text");
	wchar_t *str = CharToWchar(luaL_checkstring(L,2));
	txt->setFont(str);
	delete str;
	return 0;
}

static int text_setFontStyle(lua_State *L){
	T_Text *txt = (T_Text *)ModuleCheck(L,1,"Text");
	txt->setFontStyle((Gdiplus::FontStyle) luaL_checkinteger(L,2));
	return 0;
}

static int text_setAlignment(lua_State *L){
	T_Text *txt = (T_Text *)ModuleCheck(L,1,"Text");
	txt->setAlignment((Gdiplus::StringAlignment) luaL_checkinteger(L,2));
	return 0;
}

static int text_getPreferedSize(lua_State *L){
	T_Text *txt = (T_Text *)ModuleCheck(L,1,"Text");
	ModuleInstance(L, new Gdiplus::SizeF(txt->getPreferedSize()) ,"Size",true);
	return 1;
}

static int text_create(lua_State *L){
	T_Text *node = 0;
	wchar_t *txt = CharToWchar(luaL_checkstring(L,1));
	REAL fontSize = (REAL)luaL_checknumber(L,2);
	if(lua_isstring(L,3)){
		wchar_t *fontName = CharToWchar(luaL_checkstring(L,3));
		node = T_Text::create(txt,fontSize,fontName);
		delete fontName;
	}else{
		node = T_Text::create(txt,fontSize);
	}
	delete txt;
	ModuleInstance(L,node,"Text",false);
	return 1;
}

static int text_release(lua_State *L){
	T_Text *txt = (T_Text *)touserdata(L,1);
	if(txt){
		delete txt;
	}
	return 0;
}

int lua_opensprite(lua_State *L){
	BeginModule(L,"Text");
	InitModule(L,0,text_release);
	ModuleExtends(L,"Node");
	NormalFunction(L,"setText",text_setText);
	NormalFunction(L,"setFontSize",text_setFontSize);
	NormalFunction(L,"setColor",text_setColor);
	NormalFunction(L,"setFont",text_setFont);
	NormalFunction(L,"setFontStyle",text_setFontStyle);
	NormalFunction(L,"setAlignment",text_setAlignment);
	NormalFunction(L,"getPreferedSize",text_getPreferedSize);
	StaticFunction(L,"create",text_create);
	EndModule(L);
	return 0;
}


int lua_closesprite(lua_State *L){
	lua_pushnil(L);
	lua_setglobal(L,"Text");
	lua_pushnil(L);
	lua_setglobal(L,"Sprite");
	return 0;
}